using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Microsoft.SharePoint;
using PS.Practices.SiteBuilder.Features.Schema;
using PS.Practices.Util;

namespace PS.Practices.SiteBuilder.Features
{
#if !SANDBOX
    public class ProvisionerProvider: SPWebProvisioningProvider
    {
        public override void Provision(SPWebProvisioningProperties props)
        {
           SPWeb web = props.Web;
         
            string data = props.Data;

            if (!string.IsNullOrEmpty(data))
            {
                //try
                //{
                    Regex regex = new Regex(@"\w+#\d+");
                    if (regex.IsMatch(data)) //supplied data is a name of a web template;
                    {
                        web.ApplyWebTemplate(data);
                    }
                    else
                    { //supplied data is a file path

                        if (!Path.IsPathRooted(data))
                        {
                            string folder = EnvironmentUtil.GetWSSSiteDefFolder();
                            data = Path.Combine(folder, data);
                        }

                        ApplyScript(web, data);
                    }
                //} catch (Exception ex)
                //{
                //    Logger.Error(ex);
                //}
            }
        }

        public static void ApplyScript(SPWeb web, string scriptPath, bool templateRelative, IDictionary<string, string> properties)
        {
            if (templateRelative)
                scriptPath = Path.Combine(EnvironmentUtil.GetWSSSiteDefFolder(), scriptPath);
            ApplyScript(web, scriptPath, properties);
        }

        public static void ApplyScript(SPWeb web, string scriptPath, IDictionary<string, string> properties)
        {
            //Enforce web reopening after tempalte application through web.ApplyWebTempalte. 
            //has to be in place to support Publihsing-feature based sites in SP2010
            var interpreter = new Interpreter(properties) {ReopenWebOnApplyWebTemplate = true};
            interpreter.Process2(web, scriptPath);
        }

        public static void ApplyScript(SPWeb web, string scriptPath)
        {
            var interpreter = new Interpreter { ReopenWebOnApplyWebTemplate = true };
            interpreter.Process2(web, scriptPath);
        }
    }
#endif
}
